<?php

namespace app\jiyun\controller\order;

use app\common\model\admin\AccountModel;
use app\common\model\collect\OrderExpressGoodsModel;
use app\common\model\collect\OrderExpressModel;
use app\common\model\jiyun\OrderModel;
use app\common\model\jiyun\warehouse\WarehouseModel;
use app\common\model\jiyun\warehouse\WarehouseRegionLocationModel;
use app\common\model\shop\PlatformModel;
use app\jiyun\service\SyncOrderService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\facade\Db;

/**
 * 订单快递包裹
 * @class Order
 * @package app\jiyun\controller\order
 * @auth shirukun
 * @date 2024/11/21 16:32
 */
class OrderExpress extends Controller
{
    // 不过滤user_id
    public $check_user = false;

    /**
     * 快递包裹列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        OrderExpressModel::mQuery()->layTable(function (){
            $this->title = lang('快递包裹列表');

            // 公司列表
            if ($this->super) {
                $this->account_list = AccountModel::mk()->where(['status'=> 1])->column('title', 'id');
            }else{
                $this->account_list = [];
            }
            // 状态
            $this->status = OrderExpressModel::getStatus();
            // 平台列表
            $this->platform_list = PlatformModel::mk()->where(['status' => 1])->column('title', 'id');

        },function (QueryHelper $query){

            $query->order('id desc')->where([['status','<>',-1],['is_merge','=',0]]);
            $query->like("order_no,express_no")->equal("account_id,status");

        });
    }

    protected function _index_page_filter(&$data){
        if ($this->super) {
            // 公司列表
            $account_list = AccountModel::mk()->where(['status' => 1])->column('title', 'id');
        }else{
            // 公司列表
            $account_list = [];
        }
        // 仓库列表
        $warehouse_list = WarehouseModel::mk()->column('warehouse_c_name', 'id');
        // 状态
        $status = OrderExpressModel::getStatus();

        foreach ($data as &$item) {
            $item['company_name'] = $account_list[$item['shop_account_id']] ?? "-";
            $item['warehouse_c_name'] = $warehouse_list[$item['warehouse_id']] ?? "-";
            $item['status_title'] = $status[$item['status']] ?? "-";
            $item['is_pid'] = $item['pid'] === 0 ? '未合箱' : '已合箱';
        }
    }

    /**
     * 详情
     * @auth true
     */
    public function info()
    {
        $id = input('id');
        $order_express_goods = OrderExpressGoodsModel::mk()->where(['order_express_id'=>$id])->select()->toArray();
//        halt(json_encode($order_express_goods));
        $this->order_express_goods = json_encode($order_express_goods,320);

        OrderExpressModel::mForm("info");
    }

    /**
     * 表单前置回调
     */
    protected function _form_filter(array &$data)
    {
        // 公司列表
        if ($this->super) {
            $this->account_list = AccountModel::mk()->where(['status'=> 1])->column('title', 'id');
        }else{
            $this->account_list = [];
        }
        // 仓库列表
        $this->warehouse_list = WarehouseModel::mk()->column('warehouse_c_name', 'id');
    }

    /**
     * 包裹签收
     * @auth true
     */
    public function infoSignFor ()
    {
        $ids = $this->request->param('id');

        // 验证订单状态
        $status_arr = OrderExpressModel::mk()->where([['id','in',$ids]])->column('status');
        if(count($status_arr)>1 || implode(',',array_unique($status_arr)) != 0){
            $this->error('请选择待签收的订单');
        }

        try {

            // 更新表数据
            OrderExpressModel::where([['id','in',$ids]])->update([
                'status' => 1, // 待入库
            ]);

        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('签收成功');

    }

    /**
     * 包裹入库
     * @auth true
     */
    public function infoWarehouseIn ()
    {

        if ( $this->request->isPost() ) {

            $data = $this->request->param();

            $rule = [
                "id|".lang('订单')    =>  "require|integer",
//                "in_num|".lang('入库数量')    =>  "require|number|between:1,9999999999",
                "location_code|".lang('货位')    =>  "require|length:1,20",
            ];
            $validate = new \think\Validate;

            // 使用 rule 方法指定验证规则
            $validate->rule($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            // 包裹详情
            $OrderExpress = OrderExpressModel::mk()->find($data['id']);

            try {
                // 启动事务
                Db::startTrans();

                // 包裹更新数据
                $OrderExpressupdate = [
                    'location_code' => $data['location_code'], // 货位
                    'status'        => 2, // 状态
                    'into_time'        => date('Y-m-d H:i:s'), // 入库时间
                ];

                // 查询订单所有包裹是否全部入库
                $jiyun_order = OrderModel::mk()->where([['other_order_no','find in set',$OrderExpress['order_no']]])->find();
                if (!empty($jiyun_order)){ // 订单已推送
                    $OrderExpress_no_into_num = OrderExpressModel::mk()->where([
                        ['order_no','in',$jiyun_order['other_order_no']], // 绑定的单号
                        ['status','in',['-1','0','1']], // 未入库的状态
                    ])->count();
                    if($OrderExpress_no_into_num == 0){ // 以全部入库
                        // 更新订单表数据
                        OrderModel::mk()->where([['id','=',$jiyun_order['id']]])->update([
                            'status' => 1
                        ]);
                    }

                    // 更新订单表包裹入库数量
                    OrderModel::mk()->where([['id','=',$jiyun_order['id']]])->inc('has_express_num')->update();

                    // 绑定集运订单id
                    $OrderExpressupdate['jiyun_order_id'] = $jiyun_order['id'];
                }

                // 更新包裹表数据
                OrderExpressModel::where([['id','=',$data['id']]])->update($OrderExpressupdate);

                // 提交事务
                Db::commit();
            }catch (\Exception $e){
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('提交成功');

        } else {

            $order_id = $this->request->param('id');

            // 包裹明细详情
            $OrderInfoExpress = OrderExpressModel::mk()->find($order_id);
            if(empty($OrderInfoExpress) || $OrderInfoExpress['status'] != 1){
                $this->error('订单不存在或订单状态不符');
            }

            // 获取仓库信息
            $Warehouse = WarehouseModel::mk()->find($OrderInfoExpress['warehouse_id']);
//            halt($Warehouse);

            // 获取货位列表
            $locationList = WarehouseRegionLocationModel::mk()->where(['warehouse_id'=>$OrderInfoExpress['warehouse_id'],'status'=>20])->column('location_code','id');

            // 商品信息
            $order_express_goods = OrderExpressGoodsModel::mk()->where(['order_express_id'=>$order_id])->select()->toArray();

            $this->order_express_goods = json_encode($order_express_goods,320);
            $this->vo = $OrderInfoExpress;
            $this->Warehouse = $Warehouse;
            $this->locationList = $locationList;

            $this->fetch();
        }

    }
}
